{% extends "base.html" %}

{% block content %}
<div class="row">
    <!-- 当前时间显示 -->
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-clock"></i> 当前时间
            </div>
            <div class="card-body text-center">
                <h2 id="current-time" class="display-4">--:--:--</h2>
                <p id="current-date" class="lead"></p>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 下次铃声显示 -->
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-bell"></i> 下次铃声
            </div>
            <div class="card-body text-center">
                <h3 id="next-bell-time" class="text-primary">暂无</h3>
                <p id="next-bell-file" class="text-muted">暂无</p>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 控制按钮 -->
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-gamepad"></i> 系统控制
            </div>
            <div class="card-body">
                <div class="d-grid gap-2 d-md-flex justify-content-md-center">
                    <button id="start-system" class="btn btn-success me-md-2" type="button">
                        <i class="fas fa-play"></i> 启动系统
                    </button>
                    <button id="stop-system" class="btn btn-danger me-md-2" type="button" disabled>
                        <i class="fas fa-stop"></i> 停止系统
                    </button>
                    <button id="test-bell" class="btn btn-info me-md-2" type="button">
                        <i class="fas fa-volume-up"></i> 测试铃声
                    </button>
                    <button id="stop-play" class="btn btn-warning me-md-2" type="button">
                        <i class="fas fa-pause"></i> 停止播放
                    </button>
                    <button id="skip-bell" class="btn btn-secondary" type="button" disabled>
                        <i class="fas fa-forward"></i> 跳过下次铃声
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 星期方案设置 -->
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-calendar-alt"></i> 星期方案设置
            </div>
            <div class="card-body">
                <div class="row" id="weekday-plans">
                    <!-- 星期方案将通过JavaScript动态加载 -->
                </div>
                <div class="d-grid gap-2 d-md-flex justify-content-md-center mt-3">
                    <button id="save-weekday-plans" class="btn btn-primary" type="button">
                        <i class="fas fa-save"></i> 保存并执行
                    </button>
                    <button id="refresh-weekday-plans" class="btn btn-secondary" type="button">
                        <i class="fas fa-sync"></i> 刷新
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 运行日志 -->
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-file-alt"></i> 运行日志
            </div>
            <div class="card-body">
                <div id="log-container" style="height: 200px; overflow-y: auto; background-color: #f8f9fa; padding: 10px; border: 1px solid #dee2e6;">
                    <pre id="status-log" class="mb-0"></pre>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 更新时间显示
    function updateTime() {
        const now = new Date();
        const timeString = now.toTimeString().split(' ')[0];
        const dateString = now.toLocaleDateString('zh-CN', { 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric', 
            weekday: 'long' 
        });
        
        document.getElementById('current-time').textContent = timeString;
        document.getElementById('current-date').textContent = dateString;
    }
    
    // 获取并显示当前星期方案
    function getCurrentWeekdayPlan() {
        // 移除此函数的功能
        return;
    }
    
    // 记录日志
    function logMessage(message) {
        const logElement = document.getElementById('status-log');
        const timestamp = new Date().toTimeString().split(' ')[0];
        logElement.textContent += `[${timestamp}] ${message}\n`;
        logElement.scrollTop = logElement.scrollHeight;
    }
    
    // 加载星期方案设置
    function loadWeekdayPlans() {
        fetch('/api/weekday_plans')
            .then(response => response.json())
            .then(data => {
                // 获取所有启用的方案
                return fetch('/api/active_plans')
                    .then(response => response.json())
                    .then(plans => {
                        renderWeekdayPlans(data, plans);
                    });
            })
            .catch(error => {
                console.error('加载星期方案设置失败:', error);
                logMessage('加载星期方案设置失败: ' + error.message);
            });
    }
    
    // 渲染星期方案设置
    function renderWeekdayPlans(weekdayPlans, plans) {
        const container = document.getElementById('weekday-plans');
        const weekdays = {
            'monday': '周一',
            'tuesday': '周二',
            'wednesday': '周三',
            'thursday': '周四',
            'friday': '周五',
            'saturday': '周六',
            'sunday': '周日'
        };
        
        // 清空容器
        container.innerHTML = '';
        
        // 为每个星期几创建行
        for (const [dayKey, dayName] of Object.entries(weekdays)) {
            const selectedPlanId = weekdayPlans[dayKey] || '';
            
            // 构建方案选项
            let planOptions = '<option value="">无</option>';
            plans.forEach(plan => {
                const selected = plan.id == selectedPlanId ? 'selected' : '';
                planOptions += `<option value="${plan.id}" ${selected}>${plan.name}</option>`;
            });
            
            const rowHtml = `
                <div class="col-md-6 mb-2">
                    <div class="input-group">
                        <span class="input-group-text" style="width: 60px;">${dayName}</span>
                        <select class="form-select weekday-plan-select" data-day="${dayKey}">
                            ${planOptions}
                        </select>
                    </div>
                </div>
            `;
            container.innerHTML += rowHtml;
        }
    }
    
    // 保存星期方案设置
    function saveWeekdayPlans() {
        const selects = document.querySelectorAll('.weekday-plan-select');
        const weekdayPlans = {};
        
        selects.forEach(select => {
            const day = select.getAttribute('data-day');
            const planId = select.value;
            if (planId) {
                weekdayPlans[day] = parseInt(planId);
            } else {
                weekdayPlans[day] = null;
            }
        });
        
        fetch('/api/weekday_plans', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(weekdayPlans)
        })
        .then(response => response.json())
        .then(data => {
            logMessage('星期方案设置已保存');
            alert('星期方案设置已保存');
            // 保存成功后重新加载星期方案设置以显示保存的内容
            loadWeekdayPlans();
        })
        .catch(error => {
            console.error('保存星期方案设置失败:', error);
            logMessage('保存星期方案设置失败: ' + error.message);
            alert('保存失败: ' + error.message);
        });
    }
    
    // 更新下一个铃声显示
    function updateNextBell() {
        fetch('/api/next_bell')
            .then(response => {
                if (response.ok) {
                    return response.json();
                } else {
                    document.getElementById('next-bell-time').textContent = '暂无';
                    document.getElementById('next-bell-file').textContent = '暂无';
                    return null;
                }
            })
            .then(data => {
                if (data) {
                    document.getElementById('next-bell-time').textContent = data.time;
                    document.getElementById('next-bell-file').textContent = data.audio_file;
                }
            })
            .catch(error => {
                console.error('获取下一个铃声失败:', error);
            });
    }
    
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化时间显示
        updateTime();
        setInterval(updateTime, 1000);
        
        // 初始化下一个铃声显示
        updateNextBell();
        setInterval(updateNextBell, 5000); // 每5秒更新一次
        
        // 加载星期方案设置
        loadWeekdayPlans();
        
        // 记录初始日志
        logMessage('系统已启动');
        
        // 应用启动时自动启动系统
        logMessage('系统启动中...');
        fetch('/api/start_scheduler', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('start-system').disabled = true;
            document.getElementById('stop-system').disabled = false;
            document.getElementById('skip-bell').disabled = false;
            logMessage('系统已启动');
        })
        .catch(error => {
            console.error('启动系统失败:', error);
            logMessage('启动系统失败: ' + error.message);
        });
        
        // 绑定按钮事件
        document.getElementById('start-system').addEventListener('click', function() {
            logMessage('系统启动中...');
            // 调用启动系统的API
            fetch('/api/start_scheduler', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                this.disabled = true;
                document.getElementById('stop-system').disabled = false;
                document.getElementById('skip-bell').disabled = false;
                logMessage('系统已启动');
            })
            .catch(error => {
                console.error('启动系统失败:', error);
                logMessage('启动系统失败: ' + error.message);
            });
        });
        
        document.getElementById('stop-system').addEventListener('click', function() {
            logMessage('系统停止中...');
            // 调用停止系统的API
            fetch('/api/stop_scheduler', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                this.disabled = true;
                document.getElementById('start-system').disabled = false;
                document.getElementById('skip-bell').disabled = true;
                logMessage('系统已停止');
            })
            .catch(error => {
                console.error('停止系统失败:', error);
                logMessage('停止系统失败: ' + error.message);
            });
        });
        
        document.getElementById('test-bell').addEventListener('click', function() {
            logMessage('测试铃声播放...');
            // 获取一个测试音频文件
            fetch('/api/audio_files')
                .then(response => response.json())
                .then(files => {
                    if (files.length > 0) {
                        // 使用第一个音频文件进行测试
                        const testFile = files[0];
                        return fetch('/api/play_audio', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                file_path: testFile.path,
                                volume: 80
                            })
                        });
                    } else {
                        throw new Error('没有可用的音频文件');
                    }
                })
                .then(response => response.json())
                .then(data => {
                    logMessage('测试铃声播放完成');
                })
                .catch(error => {
                    console.error('播放测试铃声失败:', error);
                    logMessage('播放测试铃声失败: ' + error.message);
                });
        });
        
        document.getElementById('stop-play').addEventListener('click', function() {
            logMessage('停止播放...');
            // 调用停止播放的API
            fetch('/api/stop_audio', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                logMessage('已停止播放');
            })
            .catch(error => {
                console.error('停止播放失败:', error);
                logMessage('停止播放失败: ' + error.message);
            });
        });
        
        document.getElementById('skip-bell').addEventListener('click', function() {
            logMessage('跳过下次铃声...');
            // 调用跳过铃声的API
            fetch('/api/skip_next_bell', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                logMessage('已跳过下次铃声: ' + data.skipped_bell.time);
            })
            .catch(error => {
                console.error('跳过铃声失败:', error);
                logMessage('跳过铃声失败: ' + error.message);
            });
        });
        
        document.getElementById('save-weekday-plans').addEventListener('click', function() {
            saveWeekdayPlans();
        });
        
        document.getElementById('refresh-weekday-plans').addEventListener('click', function() {
            loadWeekdayPlans();
            logMessage('星期方案设置已刷新');
        });
    });
</script>
{% endblock %}